// pages/dynamicDetail/dynamicDetail.js
import {
  dynamicDetail,
  dynamicComment,
  dynamicEndorse
} from "../../api/index"
import {
  timeFormat
} from "../../utils/util"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dynamicDetail: {},
    message: "",
    isShowStatusHeader:false,  //是否展示顶部头像
    CustomBar: app.globalData.CustomBar //顶部标签高度
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.getDynamicDetail(options.dynamicId)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  scrollChange:function(e){
    let scrollTop = e.detail.scrollTop
    if(scrollTop>=100 && !this.data.isShowStatusHeader){
      this.setData({
        isShowStatusHeader:true
      })
    }
    if(scrollTop<100 && this.data.isShowStatusHeader){
      this.setData({
        isShowStatusHeader:false
      })
    }
  },
  getDynamicDetail: async function (id) {
    const result = await dynamicDetail({
      dynamicId: id
    })
    if (result) {
      result.createTime = timeFormat(result.createTime)
      for(let i in result.comments){
        result.comments[i].createTime = timeFormat(result.comments[i].createTime)
      }
      this.setData({
        dynamicDetail: result
      })
    }
  },
  commentMessageChange: function (e) {
    let message = e.detail.value
    this.setData({
      message: message
    })
  },
  commentClick: async function () {
    const dynamicId = this.data.dynamicDetail._id
    const message = this.data.message
    const result = await dynamicComment({
      dynamicId: dynamicId,
      message: message
    })
    if (result._id) {
      this.setData({
        message: ""
      })
      wx.showToast({
        title: '评论成功',
        icon:"none"
      })
      this.getDynamicDetail(dynamicId)
    }
    console.log(result)
  },
  endroseClick: async function(){
    const dynamicId = this.data.dynamicDetail._id
    const isEndorse = this.data.dynamicDetail.isEndorse
    const endorseCount = this.data.dynamicDetail.endorseCount
    let active = isEndorse===1?0:1
    let count = isEndorse===1?endorseCount-1:endorseCount+1
    const result = await dynamicEndorse({dynamicId:dynamicId,active:active})
    this.setData({
      [`dynamicDetail.isEndorse`]:isEndorse===1?0:1,
      [`dynamicDetail.endorseCount`]:count
    })
    console.log(result)
  },
  previewImg:function(e){
    //预览图片
    let index = e.currentTarget.dataset.index
    let images = this.data.dynamicDetail.images
    wx.previewImage({
      current:images[index],
      urls: images,
    }) 
  }
})